package com.yjd.api.home;
import com.yjd.comm.base.control.MobileBaseControl;
import com.yjd.comm.base.enums.DbWREnums;
import com.yjd.comm.base.model.CityModel;
import com.yjd.comm.base.service.ICityService;
import com.yjd.comm.org.service.IOrganizationService;
import com.yjd.comm.util.FrameUtil;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * Created by yjd-wap on 2017/7/10.
 */
@Controller
@Scope("prototype")
@RequestMapping("/city/")
public class CityControl extends MobileBaseControl {

    @Resource
    private ICityService cityService;

    @Resource
    private IOrganizationService organizationService;

    /**
     * 查询所有省份列表
     * @throws Exception
     */
    @RequestMapping("province/list")
    public void provinceList() throws Exception {
       List<CityModel> cityModelList =  cityService.getModelList(FrameUtil.newHashMap("parentid",0,"sort"," id asc "),DbWREnums.READ);
        successData(FrameUtil.newHashMap("provinceList",cityModelList));
    }

    /**
     * 查询所有省份列表
     * @throws Exception
     */
    @RequestMapping("exist/org")
    public void provinceOfExistOrg() throws Exception {
        List<Long> idList = organizationService.queryAllOrgCity(Collections.EMPTY_MAP);
        Set<Long> province = new HashSet<>();
        province.addAll(idList);
        province = queryParentId(province);

        List<CityModel> cityModelList = cityService.getModelList(FrameUtil.newHashMap("idList", province.toArray(), "sort"," id asc "), DbWREnums.READ);

        CityModel all = new CityModel();
        all.setId(0L);
        all.setName("全部");
        cityModelList.add(0, all);
        this.successData(FrameUtil.newHashMap("provinceList", cityModelList));
    }

    /**
     * 从第三级城市循环往上查找到对应的省份
     *
     * @param
     * @return
     * @throws
     */
    private Set<Long> queryParentId(Set<Long> idList) throws Exception {
        Set<Long> provinceId = new HashSet<>();
        List<CityModel> cityModelList =  cityService.getModelList(FrameUtil.newHashMap("idList", idList.toArray()),DbWREnums.READ);
        idList.clear();
        for(CityModel cm : cityModelList){
            if(cm.getParentid() == 0){
                provinceId.add(cm.getId());
                continue;
            }

            idList.add(cm.getParentid());
        }
        if(idList.size()>0){
            provinceId.addAll(queryParentId(idList));
        }
        return provinceId;
    }
}
